<template>
	<view class="avatar-form-container">
		<view class="flex-row-between">
			<view>头像</view>
			<view class="flex-row">
				<u-upload class="avatar" :multiple="false" @afterRead="afterRead" :maxCount="1">
					<UserAvatar />
				</u-upload>
			</view>
		</view>
	</view>
</template>

<script>
	import UserAvatar from '@/components/UserAvatar/UserAvatar.vue';
	import {
		uploadAvatar
	} from '@/api/system/user.js';
	import {
		getToken
	} from '@/utils/auth'
	export default {
		components: {
			UserAvatar,
		},
		methods: {
			// 新增图片
			async afterRead(event) {
				const {
					file
				} = event;
				const result = await this.uploadFilePromise(file.url);
				this.$store.commit("SET_AVATAR", result.data);
				uni.showToast({
					title: '操作成功',
					icon: 'none'
				})
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: uploadAvatar(),
						filePath: url,
						name: 'file',
						header: {
							['Authorization']: 'Bearer ' + getToken(),
							['entfrm']: getToken(),
						},
						success: result => {
							resolve(JSON.parse(result.data))
						}
					});
				})
			},
		}
	}
</script>

<style scoped lang="scss">
	.avatar-form-container {
		padding: 54rpx 0;
		border-bottom: 0.5px solid #f0f0f0;

		.avatar {
			width: 126rpx;
			height: 126rpx;
			border-radius: 50%;
			overflow: hidden;
		}
	}
</style>